<template>
    <div>
        <div class="thirdTabs">
            <Tabs 
            type="card" 
            closable 
            v-model="currentTab" 
            :animated="false" >
                <TabPane label="费用明细" :closable="false" :name="'0'">
                    <!-- 费用明细搜索栏 -->
                    <Row :gutter="16" class='flex-style' style='padding-bottom: 15px;'>
                        <Col span='6'>
                            绑定方
                            <Select
                                placeholder='不限'
                                v-model="filterData.binder"
                                class='flex-items'>
                                <Option :value="0">无</Option>
                                <Option :value="1">云丁绑定</Option>
                                <Option :value="2">商户绑定</Option>
                            </Select>
                        </Col>
                        <Col span='6'>
                            城市
                            <Select
                                v-model="filterData.city"
                                placeholder='不限'
                                class='flex-items'>
                                <Option v-for="(item, key, index) in citys" :value="item.name" :key="item.region_code">{{ item.name }}</Option>
                            </Select>
                        </Col>
                        <Col span='12'>
                            关键字
                            <Input  placeholder="请输入关键字" style="width: 300px" v-model="filterData.keyword"/>
                            <Button type="primary" style="margin:0 10px" @click="handleSearch">搜索</Button>
                            <Button type="primary" @click="handleAllSure">所有费用无误</Button>
                        </Col>
                    </Row>
                    <!-- 费用明细表格 -->
                    
                    <Table stripe border :columns="billInfo" :data="billInfoData" :loading="isLoading"></Table>
                    <p class="text-center margin-top-20">
                    <!--分页-->
                    <Page :total="total"
                    :page-size="size"
                    :current.sync="currentPage"
                    show-elevator
                    @on-change="getContractInfo"
                    show-total style="text-align:center"></Page>
                    <!--分页end-->
                </p>
                </TabPane>
                <TabPane :name="'1'" label="费用统计" :closable="false">
                    <!-- <div class="table-box"> -->
                    <div>
                        <Table stripe border :columns="tjColumns" :data="tjRenters" :loading="isLoading"></Table>
                    </div>
                </TabPane>
                <TabPane :name="'2'" label="争议费用" :closable="false">
                    <Table stripe border :columns="zyColumns" :data="zyRenters" :loading="isLoading"></Table>
                </TabPane>
            </Tabs>
        </div>
        <!-- 不认同model -->
        <Modal
            title="不认同"
            v-model="show"
            >
            <Form :model="form" ref="form" :rules="ruleValidate"  :label-width="120" class="padding-right-20">
                <!-- <FormItem label="应付费用" prop="accruedAmount">
                    <Input v-model="form.accruedAmount"></Input>
                </FormItem> -->
                <FormItem label="是否已收费" prop="ifPay" class="ivu-form-item-required">
                    是
                </FormItem>
                <FormItem label="备注" prop="reason" :rules="{required: true, message: '备注不能为空', trigger: 'blur'}">
                    <Input type="textarea" v-model="form.reason"></Input>
                </FormItem>
            </Form>
            <Row slot="footer">
                <Button type="text" @click="show=false">取消</Button>
                <Button type="primary" :loading="loading" @click="handleSubmit('form')">确定</Button>
            </Row>
        </Modal>
        <!-- 同意不同意model -->
        <Modal
            title="不同意"
            v-model="auditShow"
            >
            <i-input type="textarea" v-model="auditForm.reject"></i-input>
            <Row slot="footer">
                <Button type="text" @click="auditShow=false">取消</Button>
                <Button type="primary"  @click="handleAudit">确定</Button>
            </Row>
        </Modal>
    </div>
</template>

<script>
import { http, api } from '@/libs/http'
export default {
  props: {
    id: String
  },
  data () {
    const validateMobile = (rule, value, callback) => {
      if (Number(value) === 0) {
        callback()
      } else if (!Number(value)) {
        callback(new Error('请输入数字值'))
      } else {
        callback()
      }
    }
    return {
      citys: [], // 城市
      auditTitle: '',
      total: 0,
      size: 20,
      currentPage: 1,
      filterData: {}, // 搜索
      auditShow: false,
      form: {}, // 不认同
      auditForm: {}, // 同意不同意
      sureloading: false,
      loading: false,
      show: false,
      currentTab: '0',
      tjColumns: [
        {
          title: '收费项目',
          key: 'contentType',
          align: 'center',
          render: (h, p) => <span>{this.capDevice(p.row.contentType)}</span>
        },
        {
          title: '单价',
          key: 'contractPrice',
          align: 'center'
        },
        {
          title: '收费数量',
          key: 'totalCostCount',
          align: 'center'
        },
        {
          title: '收费金额（元）',
          align: 'center',
          render: (h, p) => <span>{p.row.totalCost}</span>
        }
        // invoiceNum开票数量
        // invoiceAmount开票金额
        // {
        //     title: '未开票数量',
        //     align: 'center',
        //     render: (h, p) => <span>{p.row.totalUnInvoiceCount}</span>
        // },
        // {
        //     title: '未开票金额',
        //     align: 'center',
        //     render: (h, p) => <span>{p.row.totalUnInvoiceAmount}</span>
        // }
      ], // 费用统计数据结构
      zyColumns: [
        {
          minWidth: 126,
          align: 'center',
          title: '创建日期',
          key: 'createTime',
          render: (h, params) => {
            return h('div', [
              h('div', params.row.billTime.split(' ')[0])
            ])
          }
        },
        {
          minWidth: 160,
          align: 'center',
          title: '绑定方|工单编号',
          render: (h, params) => {
            return h('div', [
              h('div', params.row.binderName),
              h('div', params.row.ticketSn)
            ])
          }
        },
        {
          minWidth: 320,
          align: 'center',
          title: '房间|房源地址',
          key: 'company_name',
          render: (h, params) => {
            return h('div', [
              h('div', params.row.roomAddr)
              // h('div', params.row.id)
            ])
          }
        },
        {
          minWidth: 160,
          align: 'center',
          title: '收费内容',
          key: 'contentType',
          render: (h, params) => {
            let tag = params.row.channelTypeName &&
                        (h('div', [
                          h('div', this.capDevice(params.row.contentType)),
                          h('div', params.row.deviceSn),
                          h('Tag', {
                            props: {
                              color: '#05bac5'
                            }
                          }, params.row.channelTypeName)
                        ]) ||
                        h('div', [
                          h('div', this.capDevice(params.row.contentType)),
                          h('div', params.row.deviceSn)
                        ]))
            return tag
          }
        },
        {
          minWidth: 120,
          align: 'center',
          title: '金额',
          key: 'amount'
        },
        {
          minWidth: 120,
          align: 'center',
          title: '单价',
          key: 'contractPrice',
          render: (h, params) => {
            let tag = params.row.channelType === 1 &&
                        (h('span', params.row.salePrice) ||
                        h('span', params.row.contractPrice))
            return tag
          }
        },
        // {
        //     minWidth: 60,
        //     align: 'center',
        //     title: '应付费用',
        //     key: 'accruedAmount'
        // },
        {
          minWidth: 120,
          align: 'center',
          title: '是否已收费',
          key: 'ifPay'
        },
        {
          minWidth: 120,
          align: 'center',
          title: '费用状态',
          key: 'statusName'
        },
        {
          minWidth: 100,
          align: 'center',
          title: '客户不认可理由',
          key: 'reason'
        },
        {
          minWidth: 100,
          align: 'center',
          title: '云丁驳回理由',
          key: 'reject'
        }
        // {
        //     minWidth: 140,
        //     align: 'center',
        //     title: '操作',
        //     fixed:'right',
        //     render: (h, params) => {
        //         const commonProperty = {
        //             style: { 'margin-right': '4px' },
        //             props: { size: 'small' }
        //         };
        //         if (params.row.statusName != '已确定') {
        //             return [
        //                 <i-button {...commonProperty} onClick={() => this.auditSuccess(params.row)}>同意</i-button>,
        //                 <i-button {...commonProperty} onClick={() => this.auditError(params.row)}>不同意</i-button>
        //             ];
        //         }
        //     }
        // }
      ], // 争议费用数据结构
      billInfo: [
        {
          minWidth: 126,
          align: 'center',
          title: '创建日期',
          key: 'createTime',
          render: (h, params) => {
            return h('div', [
              h('div', params.row.billTime.split(' ')[0])
            ])
          }
        },
        {
          minWidth: 160,
          align: 'center',
          title: '绑定方|工单编号',
          render: (h, params) => {
            return h('div', [
              h('div', params.row.binderName),
              h('div', params.row.ticketSn)
            ])
          }
        },
        {
          minWidth: 320,
          align: 'center',
          title: '房间|房源地址',
          key: 'company_name',
          render: (h, params) => {
            return h('div', [
              h('div', params.row.roomAddr)
              // h('div', params.row.id)
            ])
          }
        },
        {
          minWidth: 160,
          align: 'center',
          title: '收费内容',
          key: 'contentType',
          render: (h, params) => {
            let tag = params.row.channelTypeName &&
                        (h('div', [
                          h('div', this.capDevice(params.row.contentType)),
                          h('div', params.row.deviceSn),

                          h('Tag', {
                            props: {
                              color: '#05bac5'
                            }
                          }, params.row.channelTypeName)
                        ]) ||
                        h('div', [
                          h('div', this.capDevice(params.row.contentType)),
                          h('div', params.row.deviceSn)
                        ]))
            return tag
          }
        },
        {
          minWidth: 120,
          align: 'center',
          title: '金额',
          key: 'amount'
        },
        {
          minWidth: 120,
          align: 'center',
          title: '单价',
          key: 'contractPrice',
          render: (h, params) => {
            let tag = params.row.channelType === 1 &&
                        (h('span', params.row.salePrice) ||
                        h('span', params.row.contractPrice))
            return tag
          }
        },
        // {
        //     minWidth: 60,
        //     align: 'center',
        //     title: '应付费用',
        //     key: 'accruedAmount'
        // },
        {
          minWidth: 120,
          align: 'center',
          title: '是否已收费',
          key: 'ifPay'
        },
        {
          minWidth: 120,
          align: 'center',
          title: '费用状态',
          key: 'statusName'
        },
        {
          minWidth: 100,
          align: 'center',
          title: '客户不认可理由',
          key: 'reason'
        },
        {
          minWidth: 100,
          align: 'center',
          title: '云丁驳回理由',
          key: 'reject'
        },
        {
          minWidth: 140,
          align: 'center',
          title: '操作',
          fixed: 'right',
          render: (h, params) => {
            const commonProperty = {
              style: { 'margin-right': '4px' },
              props: { size: 'small' }
            }
            if (params.row.statusName !== '已确定') {
              return [
                <i-button {...commonProperty} onClick={() => this.Sure(params.row)}>认可</i-button>,
                <i-button {...commonProperty} onClick={() => this.noSure(params.row)}>不认可</i-button>
              ]
            }
          }
        }
      ], // 费用明细数据结构
      billInfoData: [

      ], // 费用明细table
      tjRenters: [], // 费用统计
      zyRenters: [], // 争议费用
      isLoading: false,
      ruleValidate: {
        accruedAmount: [
          {required: true, message: '应付费用不能为空', trigger: 'blur'}, {validator: validateMobile, trigger: 'blur'}
        ]
      }
    }
  },
  created () {
    this.fetchModels()
    this.getContractInfo(1)// 费用明细
    this.getStatisInfo()// 费用统计
    this.getBadStatiInfo()// 争议费用
    this.getProvincesList()
  },
  methods: {
    async getContractInfo (page) {
      if (page === 1) {
        this.currentPage = 1
      }
      this.filterData.limit = this.size
      this.filterData.offset = this.size * (page - 1) || 0
      this.loading = true
      http.request(this, api.bill_cost, [this.$props.id], this.filterData, (res, err) => {
        this.loading = false
        if (res) {
          this.billInfoData = res.rows
          this.total = res.count
        }
      })
      // this.billInfoData=(await http.fetch(this, api.bill_cost, [this.$props.id], null)).rows;
    }, // 费用明细
    async getStatisInfo () {
      this.tjRenters = (await http.fetch(this, api.bill_statis, [this.$props.id], null)).rows
    }, // 费用统计
    async getBadStatiInfo () {
      this.zyRenters = (await http.fetch(this, api.bill_dispute, [this.$props.id], null)).rows
    }, // 争议费用
    noSure (row) {
      this.form = {
        billId: row.billId,
        costIds: [row.id],
        accept: 0,
        ifPay: 0,
        updateBy: row.updateBy// 修改人id以后修改
      }
      this.show = true
    }, // 不确定
    Sure (row) {
      http.request(this, api.cost_reason, null, {accept: 1,
        billId: row.billId,
        costIds: [row.id]}, (res, err) => {
        if (err || !res) return
        this.$Message.success('修改成功')
        this.getContractInfo(1)// 费用明细
        this.getStatisInfo()// 费用统计
        this.getBadStatiInfo()// 争议费用
      })
    }, // 确定
    handleSearch () {
      this.getContractInfo()
    }, // 搜索
    handleSubmit (name) {
      this.sureloading = true
      this.$refs[name].validate((valid) => {
        if (valid) {
          http.request(this, api.cost_reason, null, this.form, (res, err) => {
            this.sureloading = false
            if (err || !res) return
            this.$Message.success('修改成功')
            this.show = false
            this.form = {}
            this.getContractInfo(1)// 费用明细
            this.getStatisInfo()// 费用统计
            this.getBadStatiInfo()// 争议费用
          })
        } else {
          this.sureloading = false
          this.$Message.error('请完整填写表单信息')
        }
      })
    }, // 不认可理由
    auditError (row) {
      this.auditForm = {
        billId: row.billId,
        costIds: [row.id],
        agree: 0,
        updateBy: row.updateBy// 修改人id以后修改
      }
      this.auditShow = true
    }, // 不同意
    auditSuccess (row) {
      let query = {
        billId: row.billId,
        costIds: [row.id],
        agree: 1,
        updateBy: row.updateBy// 修改人id以后修改
      }
      http.request(this, api.cost_reject, null, query, (res, err) => {
        this.$Message.success('修改成功')
        this.getContractInfo(1)// 费用明细
        this.getStatisInfo()// 费用统计
        this.getBadStatiInfo()// 争议费用
      })
    }, // 同意
    handleAudit (row) {
      http.request(this, api.cost_reject, null, this.auditForm, (res, err) => {
        this.$Message.success('修改成功')
        this.auditShow = false
        this.auditForm = {}
        this.getContractInfo(1)// 费用明细
        this.getStatisInfo()// 费用统计
        this.getBadStatiInfo()// 争议费用
      })
    }, // 同意提交
    capDevice (value) {
      let selectModels = JSON.parse(sessionStorage.getItem('device'))
      return selectModels.find((item) => {
        return value === item.id
      }).name
    }, // 过滤设备
    handleAllSure () {
      this.$Modal.confirm({
        title: '所有费用确认无误?',
        content: '当前页费用将会被确认无误',
        onOk: () => {
          let costIds = this.billInfoData.map(item => {
            return item.id
          })
          let query = {
            costIds: costIds,
            billId: this.$props.id,
            updateBy: 0
          }
          http.request(this, api.bill_confirm, null, query, (res, err) => {
            if (res) {
              this.$Message.success('修改成功')
              this.getContractInfo(1)// 费用明细
              this.getStatisInfo()// 费用统计
              this.getBadStatiInfo()// 争议费用
            }
          })
        }
      })
    }, // 所有费用确认
    async fetchModels () {
      let res = await http.fetch(this, api.enum, null, null)
      sessionStorage.setItem('device', JSON.stringify(res))
    }, // 设备
    async getProvincesList () {
      this.citys = await http.fetch(this, api.address_cities, null, null)
    } // 获取已有房源城市

  }
}
</script>

<style lang="less" scoped>
    .label-box {
        .label {
            display: inline-block;
            width: 120px;
            padding-left: 30px;
            margin-bottom: 20px;
            margin-right: 10px;
        }
    }
    .table-box {
        border: 1px solid #dddee1;
        margin-left: 30px;
        width: 600px;
    }
    .basic {
        font-weight: 700;
        font-size: 14px;
        margin-bottom: 20px;
    }
</style>
<style lang="less">
    .thirdTabs {
        .ivu-tabs.ivu-tabs-card>.ivu-tabs-bar .ivu-tabs-tab-active {
            background: #fff;
        }
        .ivu-tabs.ivu-tabs-card>.ivu-tabs-bar:before {
            border: none;
        }
        .table-box {
            margin-left: 0;
        }
    }
    .flex-style {
        & > .ivu-col {
            display: flex;
            align-items: center;
            .flex-items {
                flex: 1;
                margin-left: 5px;
            }
        }
    }
</style>
